package com.roadmap.util;

import java.security.Key;
import java.security.spec.AlgorithmParameterSpec;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

import org.apache.log4j.Logger;

import com.roadmap.common.RdcLogger;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class RdcEncryptor {
	private final static Logger logger = RdcLogger.getLogger(RdcEncryptor.class);
	private final static String _keyParam = "aspirant@roadmap";
	private final static byte[] _DESIV = { (byte) 0x12, (byte) 0x34,
			(byte) 0x56, (byte) 0x78, (byte) 0x90, (byte) 0xAB, (byte) 0xCD,
			(byte) 0xEF }; // 设置向量

	private static AlgorithmParameterSpec _aps; // 加密算法的参数接口，IvParameterSpec是它的一个实现
	private static Key _key;

	private final static Object _lock = new Object();
	private static RdcEncryptor _instance;

	public static RdcEncryptor getInstace() {
		if (_instance == null) {
			try {
				synchronized (_lock) {
					if (_instance == null)
						_instance = new RdcEncryptor();
				}
			}
			catch (Exception e) {
				logger.error("failed to create an instance of RdcEncryptor", e);
			}
		}
		return _instance;
	}

	private RdcEncryptor() throws Exception {
		DESKeySpec keySpec = new DESKeySpec(_keyParam.getBytes()); // 设置密钥参数
		_aps = new IvParameterSpec(_DESIV); // 设置向量
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); // 获得密钥工厂
		_key = keyFactory.generateSecret(keySpec);// 得到密钥对象
	}

	public String encode(String data) {
		try {
			Cipher enCipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); // 得到加密对象Cipher
			enCipher.init(Cipher.ENCRYPT_MODE, _key, _aps); // 设置工作模式为加密模式，给出密钥和向量
			byte[] pasByte = enCipher.doFinal(data.getBytes("utf-8"));
			BASE64Encoder base64Encoder = new BASE64Encoder();
			return base64Encoder.encode(pasByte);
		}
		catch (Exception e) {
			logger.error("failed to encode " + data, e);
		}
		return null;
	}

	public String decode(String data) {
		try {
			Cipher deCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
			deCipher.init(Cipher.DECRYPT_MODE, _key, _aps);
			BASE64Decoder base64Decoder = new BASE64Decoder();
			byte[] pasByte = deCipher.doFinal(base64Decoder.decodeBuffer(data));
			return new String(pasByte, "UTF-8");
		}
		catch (Exception e) {
			logger.error("failed to decode " + data, e);
		}
		return null;
	}

	public static void test() {
		String value = "hello";
		RdcEncryptor tools = getInstace();
		System.out.println(tools.encode(value));
		System.out.println("Decode: " + tools.decode(tools.encode(value)));
	}

}
